package com.bigfans.searchservice.service.impl;

import com.bigfans.framework.es.ElasticTemplate;
import com.bigfans.framework.es.request.SearchCriteria;
import com.bigfans.framework.es.request.SearchResult;
import com.bigfans.framework.utils.PinyinHelper;
import com.bigfans.searchservice.document.convertor.TagDocumentConverter;
import com.bigfans.searchservice.model.Tag;
import com.bigfans.searchservice.schema.mapping.TagMapping;
import com.bigfans.searchservice.service.TagSearchService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TagSearchServiceImpl implements TagSearchService {
	
	@Autowired
	private ElasticTemplate elasticTemplate;

	@Override
	public List<Tag> searchTagByKeyword(String keyword, int size) throws Exception {
		// 1. 查询条件
		BoolQueryBuilder finalQuery = QueryBuilders.boolQuery();
		// 1.1 关键字查询条件
		QueryBuilder keywdQuery = QueryBuilders.termQuery(TagMapping.FIELD_NAME + "." +TagMapping.FIELD_NAME_PINYIN, PinyinHelper.toHanyupinyin(keyword));
		finalQuery.must(keywdQuery);

		SearchCriteria searchCriteria = new SearchCriteria(finalQuery);
		searchCriteria.setIndex(TagMapping.INDEX);
		searchCriteria.setType(TagMapping.TYPE);
		searchCriteria.setFrom(0);
		searchCriteria.setSize(size);

		SearchResult<Tag> result = elasticTemplate.search(searchCriteria, new TagDocumentConverter());
		return result.getData();
	}
}
